package com.yeziji.config.support.resolver;

import com.alibaba.fastjson.JSONObject;
import com.yeziji.annotation.RequestSingleBody;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;

/**
 * 单请求体的处理
 *
 * @author hwy
 * @since 2023/09/02 15:22
 **/
public class RequestSingleBodyHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestSingleBody.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        RequestSingleBody parameterAnnotation = parameter.getParameterAnnotation(RequestSingleBody.class);
        HttpServletRequest nativeRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        if (nativeRequest == null || parameterAnnotation == null) {
            return null;
        }

        BufferedReader reader = nativeRequest.getReader();
        StringBuilder sb = new StringBuilder();
        char[] buffer = new char[1024];
        int cursor;
        while ((cursor = reader.read(buffer)) != -1) {
            sb.append(buffer, 0, cursor);
        }
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        String value = parameterAnnotation.value();
        return jsonObject.get(value);
    }
}
